//
//  DSRefreshHeaderView.m
//  zzzz
//
//  Created by rainday on 15/1/24.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "DSRefreshHeaderView.h"


#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

@interface DSRefreshHeaderView()
- (void)setState:(DSRefreshHeaderViewState)aState;

@end

@implementation DSRefreshHeaderView


- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        _lastUpdatedLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, frame.size.height-20, frame.size.width, 20.0f)];
        _lastUpdatedLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _lastUpdatedLabel.font = [UIFont systemFontOfSize:12];
        _lastUpdatedLabel.textColor = TEXT_COLOR;
        _lastUpdatedLabel.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        _lastUpdatedLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
        _lastUpdatedLabel.backgroundColor = [UIColor clearColor];
        _lastUpdatedLabel.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:_lastUpdatedLabel];
        
        
        _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 38.0f, self.frame.size.width, 20.0f)];
        _statusLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _statusLabel.font = [UIFont boldSystemFontOfSize:13.0f];
        _statusLabel.textColor = TEXT_COLOR;
        _statusLabel.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        _statusLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
        _statusLabel.backgroundColor = [UIColor clearColor];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_statusLabel];
       
        
        _arrowImage = [CALayer layer];
        _arrowImage.frame = CGRectMake(25.0f, frame.size.height - 45.0f, 30.0f, 55.0f);
        _arrowImage.contentsGravity = kCAGravityResizeAspect;
        _arrowImage.contents = (id)[UIImage imageNamed:@"blackArrow.png"].CGImage;
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            _arrowImage.contentsScale = [[UIScreen mainScreen] scale];
        }
#endif
        
        [[self layer] addSublayer:_arrowImage];
        
        
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.frame = CGRectMake(25.0f, frame.size.height - 28.0f, 20.0f, 20.0f);
        [self addSubview:_activityView];
        
        [self setState:DSRefreshHeaderViewStateNormal];
    }
    
    
    return self;

}

#pragma mark Setter

- (void)refreshLastUpdatedDate{
    if ([_delegate respondsToSelector:@selector(dsRefreshTableHeaderDataSourceLastUpdated:)]) {
        
        NSDate *date = [_delegate dsRefreshTableHeaderDataSourceLastUpdated:self];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setAMSymbol:@"上午"];
        [formatter setPMSymbol:@"下午"];
        [formatter setDateFormat:@"yyyy-MM-dd a hh:mm"];
        _lastUpdatedLabel.text = [NSString stringWithFormat:@"上次更新时间: %@", [formatter stringFromDate:date]];
        [[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"DSRefreshTableView_LastRefresh"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
    } else {
        
        _lastUpdatedLabel.text = nil;
        
    }

}


- (void)setState:(DSRefreshHeaderViewState)aState{
    switch (aState) {
        case DSRefreshHeaderViewStateNormal:
            if (_state == DSRefreshHeaderViewStatePulling) {
                [CATransaction begin];
                [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
                _arrowImage.transform = CATransform3DIdentity;
                [CATransaction commit];
                
            }
            
            _statusLabel.text = NSLocalizedString(@"下拉刷新", @"下拉刷新");
            [_activityView stopAnimating];
            [CATransaction begin];
            [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
            _arrowImage.hidden = NO;
            _arrowImage.transform = CATransform3DIdentity;
            [CATransaction commit];
            [self refreshLastUpdatedDate];
            
            break;
        case DSRefreshHeaderViewStateLoading:
            _statusLabel.text = NSLocalizedString(@"正在刷新...", @"正在刷新...");
            [_activityView startAnimating];
            [CATransaction begin];
            [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
            _arrowImage.hidden = YES;
            [CATransaction commit];
            break;
        case DSRefreshHeaderViewStatePulling:
            _statusLabel.text = NSLocalizedString(@"松开刷新数据", @"松开刷新数据");
            [CATransaction begin];
            [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
            _arrowImage.transform = CATransform3DMakeRotation((M_PI/180.0)*180.0f, 0.0, 0.0, 1.0);
            [CATransaction commit];
            
            
            break;
        default:
            break;
    }
    
    _state = aState;

}


#pragma mark ScrollView Methods

- (void)dsRefreshScrollViewDidScroll:(UIScrollView *)scrollView{
    if (_state == DSRefreshHeaderViewStateLoading) {
        CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
        offset = MIN(offset, 80);
        scrollView.contentInset = UIEdgeInsetsMake(offset, 0, 0, 0);
        
    }else if (scrollView.isDragging){
        BOOL _isLoading = NO;
        if ([_delegate respondsToSelector:@selector(dsRefreshTableHeaderDataSourceIsLoading:)]) {
            _isLoading = [_delegate dsRefreshTableHeaderDataSourceIsLoading:self];
        }
        
        if (_state == DSRefreshHeaderViewStatePulling && scrollView.contentOffset.y >-65.0f && scrollView.contentOffset.y< 0 && !_isLoading) {
            [self setState:DSRefreshHeaderViewStateNormal];
        }else if(_state == DSRefreshHeaderViewStateNormal && scrollView.contentOffset.y<-65.0f && !_isLoading){
            [self setState:DSRefreshHeaderViewStatePulling];
        }
        
        if (scrollView.contentInset.top !=0 ) {
            scrollView.contentInset = UIEdgeInsetsZero;
            
        }
        
    
    }

}

- (void)dsRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView{

    
    BOOL _loading = NO;
    if ([_delegate respondsToSelector:@selector(dsRefreshTableHeaderDataSourceIsLoading:)]) {
        _loading = [_delegate dsRefreshTableHeaderDataSourceIsLoading:self  ];
    }
    
    if (scrollView.contentOffset.y <= - 65.0f && !_loading) {
        
        if ([_delegate respondsToSelector:@selector(dsRefreshTableHeaderDidTriggerRefesh:)]) {
            [_delegate dsRefreshTableHeaderDidTriggerRefesh:self];
        }
        
        [self setState:DSRefreshHeaderViewStateLoading];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        scrollView.contentInset = UIEdgeInsetsMake(80.0f, 0.0f, 0.0f, 0.0f);
        [UIView commitAnimations];
        
    }
}

- (void)dsRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
    [UIView commitAnimations];

    [self setState:DSRefreshHeaderViewStateNormal];

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
